package web

import (
	"fmt"
	"gitee.com/flycash/xiaohongshu-demo/internal/domain"
	"gitee.com/flycash/xiaohongshu-demo/internal/service"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type ArticleController struct {
	service service.ArticleService
}

func NewArticleController(service service.ArticleService) *ArticleController {
	return &ArticleController{
		service: service,
	}
}

func (a *ArticleController) RegisterRoutes(server *gin.Engine) {
	article := server.Group("/article")
	article.POST("/new", a.Save)
	article.POST("/publish", a.Publish)
	article.GET("/new", a.SavePage)
	article.Any("/publish_success", func(c *gin.Context) {
		c.String(http.StatusOK, "发表成功")
	})
	article.Any("/publish_failed", func(c *gin.Context) {
		c.String(http.StatusOK, "发表失败")
	})
}

func (a *ArticleController) Publish(c *gin.Context) {
	var art ArticleVO
	c.Bind(&art)
	// 理论上是有一些输入校验的
	//if art.Title == "" {
	//
	//}
	fmt.Printf("这是标题：%s \n这是内容：%s\n", art.Title, art.Content)
	err := a.service.Publish(c.Request.Context(), domain.Article{
		Id:      art.Id,
		Title:   art.Title,
		Content: art.Content,
		Author:  123,
	})
	if err != nil {
		c.Redirect(http.StatusTemporaryRedirect, "/article/publish_failed")
		return
	}
	c.Redirect(http.StatusTemporaryRedirect, "/article/publish_success")

}

func (a *ArticleController) Save(c *gin.Context) {
	var art ArticleVO
	err := c.Bind(&art)
	if err != nil {
		log.Println(err)
		return
	}
	// 理论上是有一些输入校验的
	//if art.Title == "" {
	//
	//}
	fmt.Printf("这是标题：%s \n这是内容：%s\n", art.Title, art.Content)
	id, err := a.service.Save(c.Request.Context(), domain.Article{
		Id:      art.Id,
		Title:   art.Title,
		Content: art.Content,
		Author:  123,
	})
	if err != nil {
		c.String(http.StatusInternalServerError, "系统错误")
		return
	}
	c.String(http.StatusOK, fmt.Sprintf("%d", id))
}

func (a *ArticleController) SavePage(c *gin.Context) {
	c.HTML(http.StatusOK, "write_article.gohtml", nil)
}

// VO => view object
type ArticleVO struct {
	Id      int64  `form:"id"`
	Title   string `form:"title"`
	Content string `form:"content"`
}
